package logic

import (
	"context"
	"yuekaoHouse/api/pkg"
	"yuekaoHouse/house_srv/house"

	"yuekaoHouse/api/internal/svc"
	"yuekaoHouse/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsCodeLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSendSmsCodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsCodeLogic {
	return &SendSmsCodeLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SendSmsCodeLogic) SendSmsCode(req *types.SendSmsCodeRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 短信发送

	//判断手机号格式
	boo := pkg.MobileType(req.Mobile)
	if boo == false {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "手机号格式错误",
			Data: nil,
		}, nil
	}

	//短信限流
	limit, err := l.svcCtx.HouseSrv.SmsCodeLimit(l.ctx, &house.SmsCodeLimitRequest{Mobile: req.Mobile})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "服务器错误",
			Data: nil,
		}, nil
	}
	if limit.SmsLimit == false {
		return &types.RegMsgResponse{
			Cre:  -2,
			Mag:  "短信限流：一分钟内一次",
			Data: nil,
		}, nil
	}

	//生成短信验证码
	code := pkg.NumString()
	//调用第三方短信发送
	pkg.SendSmsCode(req.Mobile, code)

	_, err = l.svcCtx.HouseSrv.SendSmsCode(l.ctx, &house.SendSmsCodeRequest{
		Mobile: req.Mobile,
		Sale:   req.Sale,
		Code:   code,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:  -1,
			Mag:  "短信发送失败",
			Data: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Cre:  0,
		Mag:  "短信发送成功",
		Data: nil,
	}, err
}
